import classNames from 'classnames';
import { useRouter } from 'next/navigation';
import { type MouseEvent, type ReactNode } from 'react';
import useOffcanvas from 'hooks/useOffcanvas';
import { TMetadata } from '@/types';
import { UserIdH5PageContext } from '@/contexts/mobile/userId';

export default function BtnUserIdH5Page({
  path,
  iName = 'signpost',
  name,
  content,
  fn,
  isLoading,
  metadata,
}: {
  path?: string;
  iName?: string;
  name: string;
  content?: ReactNode;
  fn?: () => void;
  isLoading?: boolean;
  metadata?: TMetadata;
}) {
  const router = useRouter();
  const { showOffcanvas } = useOffcanvas();

  function onClickLink(e: MouseEvent<HTMLDivElement>) {
    e.stopPropagation();
    e.preventDefault();

    if (path) {
      router.push(path);
    } else if (fn) {
      if (isLoading) {
        return;
      }

      fn();
    } else if (content && metadata) {
      showOffcanvas({
        title: name,
        content: (
          <UserIdH5PageContext.Provider value={{ metadata }}>
            {content}
          </UserIdH5PageContext.Provider>
        ),
      });
    }
  }

  return (
    <div
      onClick={onClickLink}
      className={classNames(
        'd-flex align-items-center gap-4 justify-content-between p-2 btn',
      )}
    >
      <div className="hstack gap-3 align-items-center">
        <div>
          <i className={`bi bi-${iName}`}></i>
        </div>
        <div>{name}</div>
      </div>
      <div>
        {fn ? (
          isLoading ? (
            <span
              className="spinner-border spinner-border-sm text-secondary"
              role="status"
              aria-hidden="true"
            ></span>
          ) : (
            <i className="bi bi-chevron-right"></i>
          )
        ) : (
          <i className="bi bi-chevron-right"></i>
        )}
      </div>
    </div>
  );
}
